package com.example.mallsystem1104.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mallsystem1104.constants.Constants;
import com.example.mallsystem1104.entity.Good;
import com.example.mallsystem1104.entity.Order;
import com.example.mallsystem1104.entity.OrderGoods;
import com.example.mallsystem1104.entity.OrderItem;
import com.example.mallsystem1104.exception.ServiceException;
import com.example.mallsystem1104.mapper.*;
import com.example.mallsystem1104.utils.TokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.example.mallsystem1104.constants.RedisConstants.GOOD_TOKEN_KEY;

/**
 * @Author zy
 * @Date 2024/12/12 16:17
 * @packageName:com.example.mallsystem1104.service
 * @ClassName:OrderService
 */
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Resource
    private StandardMapper standardMapper;

    @Resource
    private GoodMapper goodMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CartService cartService;

    public String saveOrder(Order order) {
        order.setUserId(TokenUtils.getCurrentUser().getId());
        String orderNo= DateUtil.format(new DateTime(),"yyyyMMddHHmmss"+ RandomUtil.randomNumbers(0));
        order.setOrderNo(orderNo);
        order.setCreateTime(DateUtil.now());
        orderMapper.insert(order);


        OrderGoods orderGoods=new OrderGoods();
        orderGoods.setOrderId(order.getId());
        //遍历order里携带的goods数组，并用OrderItem对象来接
        String goods=order.getGoods();
        List<OrderItem> orderItems= JSON.parseArray(goods,OrderItem.class);
        for(OrderItem orderItem:orderItems){
            long goodId=orderItem.getId();
            String standard=orderItem.getStandard();
            int num=orderItem.getNum();
            orderGoods.setGoodId(goodId);
            orderGoods.setStandard(standard);
            orderGoods.setCount(num);
            //插入到order_good表
            orderGoodsMapper.insert(orderGoods);
        }
        //清空购物车
        cartService.removeById(order.getCartId());
        return orderNo;
    }

    public void payOrder(String orderNo) {
        //更改订单状态为已支付
        orderMapper.payOrder(orderNo);
        //给对应的规格减库存
        Map<String,Object> orderMap=orderMapper.selectByOrderNo(orderNo);
        int count= (int) orderMap.get("count");
        Object goodIdObj=orderMap.get("goodId");
        Long goodId=null;
        if(goodIdObj instanceof Long){
            goodId=(Long) goodIdObj;
        }else if(goodIdObj!=null){
            try {
                goodId=Long.parseLong(goodIdObj.toString());
            } catch (NumberFormatException e) {
                throw new ServiceException(Constants.CODE_500,"商品id不正确");
            }
        }

        if (goodId==null){
            throw new ServiceException(Constants.CODE_500,"商品id不存在");
        }

        String standard = (String) orderMap.get("standard");
        //查询库存
        int store=standardMapper.getStore(goodId,standard);
        if(store<count){
            throw new ServiceException(Constants.CODE_500,"库存不足");
        }
        standardMapper.deductStore(goodId,standard,store-count);

        //给对应的商品加销量和销售额
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper=new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getOrderNo, orderNo);
        Order one = getOne(orderLambdaQueryWrapper);
        BigDecimal totalPrice = one.getTotalPrice();
        goodMapper.saleGood(goodId,count,totalPrice);

        //给redis增销量
        String redisKey=GOOD_TOKEN_KEY+goodId;
        ValueOperations<String, Good> valueOperations=redisTemplate.opsForValue();
        Good good = valueOperations.get(redisKey);
        if(!ObjectUtils.isEmpty(good)){
            good.setSales(good.getSales()+count);
            valueOperations.set(redisKey,good);
        }
    }

    public Object selectByUserId(int userid) {
        return orderMapper.selectByUserId(userid);
    }

    public Map<String,Object> selectByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    public void delivery(String orderNo) {
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        orderLambdaUpdateWrapper.eq(Order::getOrderNo,orderNo).set(Order::getState,"已发货");

        update(orderLambdaUpdateWrapper);
    }

    public boolean receiveOrder(String orderNo) {
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        orderLambdaUpdateWrapper.eq(Order::getOrderNo,orderNo).set(Order::getState,"已收货");
        return update(orderLambdaUpdateWrapper);

//        return orderMapper.receiveOrder(orderNo);

    }
}
